<?php

class Pagination {
    private $count;
    private $items;
    private $baseurl;

    const ITEMS_PER_PAGE = 10;

    public function __construct($count , $baseurl , $items = self::ITEMS_PER_PAGE) {
        $this->count = $count;
        $this->items = $items;
        $this->baseurl = $baseurl;
    }

    public function render() {
        $pages = ceil($this->count / $this->items);
        $links = "";
        for($i = 1 ; $i <= $pages ; $i++)
            $links .= '<a class="pagination" href="'.$this->baseurl.'?page='.$i.'">'.$i.'</a>&nbsp;&nbsp;';
        echo $links;
    }
}

class Controller {
    public $auth = null;
    //public static $PATH = "http://milestone.if.itb.ac.id/web/215/13508040/";
    public static $PATH = "http://localhost/progin-1/tugas2/";
    protected $allowed = null;

    public function __construct() {
        session_start();
        /*if (isset($_COOKIE['session_id'])) {
        }
        else {
        }*/
        if (isset($_SESSION['auth'])) {
            $this->auth = $_SESSION['auth'];
            $id = $this->auth->id;
            $this->auth->loadFromQuery("SELECT * FROM user WHERE id = $id LIMIT 1;");
        }
    }

    public function getName() {
        $path = explode("/", $_SERVER['PATH_INFO']);
        return $path[1];
    }

    public function getMethod() {
        $path = explode("/", $_SERVER['PATH_INFO']);
        return $path[2];
    }

    public function __call($name , $args) {
        $this->render('error' , array('errorMessage' => "The path does not exist"));
    }

    public function showError($message = "") {
        $this->render('error' , array('errorMessage' => $message));
    }

    protected function isAllowed() {
        if ($this->auth != NULL && in_array($this->auth->role->name , $this->allowed))
            return true;
        else
            return false;
    }

    public function redirect($path) {
        header( "HTTP/1.1 301 Moved Permanently" );
        header( "Location: " . $path );
        die();
    }

    protected function render($viewName , $params = NULL) {
        if ($params === null) {
        }
        else {
            extract($params , EXTR_SKIP);
        }

        include "views/" . $viewName . ".php";
    }


    public function createUrl($path) {
        return self::$PATH . 'index.php/' . $path;
    }
}

?>
